//
//  ViewController.m
//  MNReprotDemo
//
//  Created by Chenly on 13-12-26.
//  Copyright (c) 2013年 Chenly. All rights reserved.
//

#import "ViewController.h"

#define kViewHeight CGRectGetHeight(self.view.frame)
#define kViewWidth CGRectGetWidth(self.view.frame)

@interface ViewController ()
{
    BOOL sortable;              //可排序
    MNReportView *reportView;   
    UILabel *descriptionLabel;
    NSInteger selectedTabIndex;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	   
    descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 0)];
    descriptionLabel.font = [UIFont systemFontOfSize:12.0];
    descriptionLabel.lineBreakMode = NSLineBreakByCharWrapping;
    descriptionLabel.numberOfLines = 0;
    
    UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, kViewHeight - 49, kViewWidth, 49)];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    for (int i = 0; i < 6; i ++) {
        
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:[NSString stringWithFormat:@"效果%d", i + 1] image:nil tag:i + 1];
        [items addObject:item];
    }
    [tabBar setItems:items];
    tabBar.delegate = self;
    
    reportView = [[MNReportView alloc] initWithFrame:CGRectMake(10, 20, 300, 0)];   //也可以使用：reportView = [[MNReportView alloc] initWithFrame:dataSource:];来初始化
    
    [self.view addSubview:descriptionLabel];
    [self.view addSubview:tabBar];
    [self.view addSubview:reportView];
    
    [tabBar setSelectedItem:items[0]];
    [self tabBar:tabBar didSelectItem:items[0]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    if (selectedTabIndex == item.tag) {
        
        return;
    }
    
    switch (item.tag) {
        case 1:
            [self reloadTable1];
            break;
        case 2:
            [self reloadTable2];
            break;
        case 3:
            [self reloadTable3];
            break;
        case 4:
            [self reloadTable4];
            break;
        case 5:
            [self reloadTable5];
            break;
        case 6:
            [self reloadTable6];
            break;
        default:
            break;
    }
    
    selectedTabIndex = item.tag;
}

#pragma mark - reload table

- (void)fitReportSize
{
    [descriptionLabel sizeToFit];
    CGRect rect = descriptionLabel.frame;
    rect.origin.y = kViewHeight - 49 - CGRectGetHeight(rect);
    descriptionLabel.frame = rect;
    
    CGFloat reportHeight = rect.origin.y - 20.0;
    rect = reportView.frame;
    rect.size.height = reportHeight;
    reportView.frame = rect;
}

- (void)reloadTable1
{
    descriptionLabel.text = @"使用默认风格：可以修改setDefaultStyle中代码，设置表格默认风格，所有未设置的部分都按照默认风格展示。";
    [self fitReportSize];
    
    MNReportData *reportData = [MNReportData alloc];
    
    //填充数据内容，headerDatas、bodyDatas都是二维数组，里面存放的MNReportGrid代表每个单元格
    NSMutableArray *headerDatas = [NSMutableArray array];
    NSMutableArray *bodyDatas = [NSMutableArray array];
    for (int rowIndex = 0; rowIndex < 10; rowIndex++) {
        
        NSMutableArray *reportRow = [NSMutableArray array];
        for (int colIndex = 0; colIndex < 10; colIndex++) {
            
            MNReportGrid *reportGrid = [MNReportGrid alloc];
            reportGrid.text = [NSString stringWithFormat:@"第%d行第%d列", rowIndex, colIndex];
            
            [reportRow addObject:reportGrid];
        }
        
        if (rowIndex < 1) {
            //表头
            [headerDatas addObject:reportRow];
        }
        else
        {
            //表体
            [bodyDatas addObject:reportRow];
        }
    }
    reportData.headerDatas = headerDatas;
    reportData.bodyDatas = bodyDatas;
    
    reportView.dataSource = reportData;
    reportView.delegate = nil;
    [reportView reload];
    sortable = NO;
}

- (void)reloadTable2
{
    descriptionLabel.text = @"使用dataSource设置风格： 颜色字符串格式：(1).六位数字(例:887788) (2).0x887788 （3）#FF778877(截取后六位) 若不适配可以修改.m中的colorFromHexString方法。\n表格的frame.height = 0 则表格自动拉为最长";
    [self fitReportSize];
    
    MNReportData *reportData = [MNReportData alloc];
    
    NSMutableArray *bodyDatas = [NSMutableArray array];
    for (int rowIndex = 0; rowIndex < 6; rowIndex++) {
        
        NSMutableArray *reportRow = [NSMutableArray array];
        for (int colIndex = 0; colIndex < 4; colIndex++) {
            
            MNReportGrid *reportGrid = [MNReportGrid alloc];
            reportGrid.text = [NSString stringWithFormat:@"第%d行第%d列", rowIndex, colIndex];
            
            [reportRow addObject:reportGrid];
        }
        
        if (rowIndex == 0) {
            
            reportData.headerDatas = @[reportRow];
            reportData.headerRowHeight = 50.0;
            reportData.headerTextAlignment = NSTextAlignmentLeft;
            reportData.headerFontSize = 17.0;
            reportData.headerBackgroundColor = @"#FF336699";
        }
        else
        {
            [bodyDatas addObject:reportRow];
        }
    }
    reportData.bodyDatas = bodyDatas;
    reportData.gridHeight = 20.0;
    reportData.gridWidth = 60.0;
    reportData.bodyFontSize = 8.0;
    reportData.bodyBackgroundColor = @"#FF996633";
    reportData.bodyTextAlignment = NSTextAlignmentRight;
    reportData.bodyTextColor = @"#FF00FF00";
    
    reportData.leftWidth = 120.0;
    
    reportData.borderlineColor = @"#FF000000";
    reportData.topBorderLineWidth = 0.0;
    reportData.bottomBorderLineWidth = 5.0;
    reportData.leftBorderLineWidth = 0;
    reportData.rightBorderLineWidth = 0;
    
    reportView.dataSource = reportData;
    reportView.delegate = nil;
    [reportView reload];
    sortable = NO;
}

- (void)reloadTable3
{
    descriptionLabel.text = @"通过设置MNReportGrid来设置每一个单元格的背景色，字体等属性。\n通过设置widthSizeFitType和heightSizeFitType来设置当实际表格宽度小于设地的Frame时候调整单元格宽度高度的方式.\n报表可以响应点击和长按事件(实现<MNReportViewTouchDelegate>代理)，可以获取被点击的label，label为自定义扩展的label有行和列的索引";
    [self fitReportSize];
    
    MNReportData *reportData = [MNReportData alloc];
    
    NSMutableArray *headerDatas = [NSMutableArray array];
    NSMutableArray *bodyDatas = [NSMutableArray array];
    for (int rowIndex = 0; rowIndex < 5; rowIndex++) {
        
        NSMutableArray *reportRow = [NSMutableArray array];
        for (int colIndex = 0; colIndex < 3; colIndex++) {
            
            MNReportGrid *reportGrid = [MNReportGrid alloc];
            reportGrid.text = [NSString stringWithFormat:@"第%d行第%d列", rowIndex, colIndex];
            
            if (rowIndex % 2 == 0) {
                
                reportGrid.backgroundColor = @"#FF336699";
            }
            else
            {
                reportGrid.backgroundColor = @"#FF996633";
            }
            if (colIndex % 2 == 0) {
                
                reportGrid.textColor = @"#FFFFCCAA";
            }
            else
            {
                reportGrid.textColor = @"#FFAACCFF";
            }
            if (rowIndex == colIndex) {
                
                reportGrid.fontSize = 20.0;
                reportGrid.bold = YES;
            }
            if (colIndex == 1) {
                
                reportGrid.underline = YES;
            }
            
            [reportRow addObject:reportGrid];
        }
        
        if (rowIndex < 1) {
            [headerDatas addObject:reportRow];
        }
        else
        {
            [bodyDatas addObject:reportRow];
        }
    }
    reportData.headerDatas = headerDatas;
    reportData.bodyDatas = bodyDatas;
    
    reportData.widthSizeFitType = MNReportWidthSizeFitTypeWithoutLeft; //第一列宽度不变，其他列拉伸
    reportData.heightSizeFitType = MNReportHeightSizeFitTypeAll;       //全部行拉伸
    
    reportView.dataSource = reportData;
    reportView.delegate = self;
    [reportView reload];
    sortable = NO;
}

- (void)reloadTable4
{
    descriptionLabel.text = @"可以通过设置reportGrid.image来设置单元格显示图片。\n可以通过设置reportData.colWidthArray来配置每一列不同列宽,配置列宽后若实际表格宽度小于设定的frame.width时，则展示实际大小(reportData.widthSizeFitType = MNReportWidthSizeFitTypeNone).";
    [self fitReportSize];
    
    MNReportData *reportData = [MNReportData alloc];
    
    //设置每列列宽
    NSMutableArray *colWidthArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithFloat:80.0], [NSNumber numberWithFloat:40.0], [NSNumber numberWithFloat:60.0], [NSNumber numberWithFloat:110.0], nil];
    reportData.colWidthArray = colWidthArray;
    
    NSMutableArray *bodyDatas = [NSMutableArray array];
    for (int rowIndex=0; rowIndex<7; rowIndex++) {
        
        NSMutableArray *reportRow = [NSMutableArray array];
        for (int colIndex = 0; colIndex < 4; colIndex++) {
            
            MNReportGrid *reportGrid = [MNReportGrid alloc];
            reportGrid.text = [NSString stringWithFormat:@"第%d行第%d列", rowIndex, colIndex];
            
            if (colIndex == 1) {
                
                if (rowIndex == 0) {
                    
                    reportGrid.text = @"图片";
                }
                else
                    reportGrid.image = [UIImage imageNamed:[NSString stringWithFormat:@"menu_%d.png", rowIndex]];
            }
            
            [reportRow addObject:reportGrid];
        }
        
        if (rowIndex == 0) {
            
            reportData.headerDatas = [NSArray arrayWithObject:reportRow];
        }
        else
        {
            [bodyDatas addObject:reportRow];
        }
    }
    reportData.bodyDatas = bodyDatas;
    
    reportView.dataSource = reportData;
    reportView.delegate = nil;
    [reportView reload];
    sortable = NO;
}

- (void)reloadTable5
{
    descriptionLabel.text = @"表头可多行，可以跨列。\n可以通过设置reportData.isAutoFitHeaderHeight/isAutoFitBodyHeight,来让表头和表体自适应行高(单元格字体过多，设定的高度无法完全展示时候自动拉高),自适应行高时，若出现表实际大小小于设定frame的情况，则当表头自适应行高时候不拉伸表头,当表体自适应行高时候全部不拉伸。";
    [self fitReportSize];
    
    MNReportData *reportData = [MNReportData alloc];
    
    NSMutableArray *bodyDatas = [NSMutableArray array];
    NSMutableArray *headerDatas = [NSMutableArray array];
    
    //设置各列列宽
    NSMutableArray *colWidthArray = [NSMutableArray arrayWithObjects:@70.0, @70.0, @60.0, @60.0, @50.0, @40.0, @80.0, @60.0, @60.0, @40.0, nil];
    reportData.colWidthArray = colWidthArray;
    
    for (int rowIndex = 0; rowIndex < 8; rowIndex++) {
        
        NSMutableArray *reportRow = [NSMutableArray array];
        for (int colIndex = 0; colIndex < 10; colIndex++) {
            
            MNReportGrid *reportGrid = [MNReportGrid alloc];
            
            NSMutableString *text = [[NSMutableString alloc] initWithFormat:@"第%d行第%d列", rowIndex, colIndex];
            
            if (colIndex == 0) {
                
                if (rowIndex == 0) {
                    
                    reportGrid.text = @"跨列";
                }
                else if (rowIndex == 1)
                {
                    reportGrid.text = @"表头自适应行高";
                }
                else
                {
                    for (int i = 1; i < rowIndex; i++) {
                        
                        [text appendFormat:@"第%d行第%d列", rowIndex, colIndex];
                    }
                    reportGrid.text = text;
                }
            }
            else
            {
                if (rowIndex == 0) {
                    
                    if (colIndex == 1) {
                        
                        reportGrid.colspans += 0;
                        reportGrid.text = @"一列";
                    }
                    if (colIndex == 2) {
                        
                        reportGrid.colspans += 1; //单元格跨列设置
                        reportGrid.text = @"二列";
                    }
                    if (colIndex == 4) {
                        
                        reportGrid.colspans += 2;
                        reportGrid.text = @"三列";
                    }
                    if (colIndex == 7) {
                        
                        reportGrid.colspans += 2;
                        reportGrid.text = @"三列";
                    }
                    colIndex += reportGrid.colspans;
                }
                else
                    reportGrid.text = text;
            }
            
            
            [reportRow addObject:reportGrid];
        }
        
        if (rowIndex < 2) {
            
            [headerDatas addObject:reportRow];
        }
        else
        {
            [bodyDatas addObject:reportRow];
        }
    }
    reportData.headerDatas = headerDatas;
    reportData.bodyDatas = bodyDatas;
    reportData.autoFitHeaderHeight = YES;    //表头自适应行高
    reportData.autoFitBodyHeight = YES;
    
    reportView.dataSource = reportData;
    reportView.delegate = nil;
    [reportView reload];
    sortable = NO;
}

- (void)reloadTable6
{
    descriptionLabel.text = @"排序功能：先通过[table setSortedArray:(NSArray *)sortedArray colIndex:(NSInteger)colIndex];设置排序数组，再通过[table sortInCol:label.colIndex];开始排序。";
    // *(参数sortedArray：排序完后行的索引数组：例如：要排序的列的值为[1(一), 3(二), 9(三), 6(四), 8(五)], 排序后为[1(一), 3(二), 6(四), 8(五), 9(三)]那么应传递的数组为:[1, 2, 4, 5, 3]
    [self fitReportSize];
    
    MNReportData *reportData = [MNReportData alloc];
    
    NSMutableArray *headerDatas = [NSMutableArray array];
    NSMutableArray *bodyDatas = [NSMutableArray array];
    
    for (int rowIndex = 0; rowIndex < 20; rowIndex++) {
        
        NSMutableArray *reportRow = [NSMutableArray array];
        
        for (int colIndex = 0; colIndex < 10; colIndex++) {
            
            MNReportGrid *reportGrid = [MNReportGrid alloc];
            
            if (rowIndex == 0) {
                
                if (colIndex == 0) {
                    
                    reportGrid.text = @"点击表头排序";
                }
                else
                    reportGrid.text = [NSString stringWithFormat:@"第%d列", colIndex];
            }
            else
            {
                if (colIndex == 0) {
                    
                    reportGrid.text = [NSString stringWithFormat:@"第%d行", rowIndex];
                }
                else
                    reportGrid.text = [NSString stringWithFormat:@"%d", arc4random() % 1000];
            }
            
            [reportRow addObject:reportGrid];
        }
        
        if (rowIndex < 1) {
            //表头
            [headerDatas addObject:reportRow];
        }
        else
        {
            //表体
            [bodyDatas addObject:reportRow];
        }
    }
    reportData.headerDatas = headerDatas;
    reportData.bodyDatas = bodyDatas;
    
    reportView.dataSource = reportData;
    reportView.delegate = self;
    [reportView reload];
    sortable = YES;
}

#pragma mark - MNReportView touch delegate

//代理方法 单击报表触发事件 table为被点击的报表 label为被点击的label 可能点击到线上会导致label = nil
- (void)MNReportView:(MNReportView*)table clickInLabel:(MNReportLabel *)label
{
    if (label == nil) {
        
        NSLog(@"nil");
    }
    else
    {
        if (sortable) {
            
            if (label.row == 0 && label.col > 0) {
                
                if (label.col != table.currentSort.index) {
                    
                    MNReportSort *sort = [[MNReportSort alloc] initWithSortedArray:[self arraySortedByAscInCol:label.col] type:MNReportSortTypeDSC index:label.col];
                    [table addSort:sort];
                }
                [table sortAtIndex:label.col];
            }
        }
        else
        {
            [self alert:label type:0];
        }
    }
}

//长按事件，其它同上
- (void)MNReportView:(MNReportView*)table longPressInLabel:(MNReportLabel *)label
{
    if (label == nil) {
        
        NSLog(@"nil");
    }
    else
    {
        if (!sortable) {
            
            [self alert:label type:1];
        }
    }
}

#pragma mark - alert

- (void)alert:(MNReportLabel *)label type:(NSInteger)type
{
    static UIAlertView *alertView;
    if (alertView == nil) {
        
        alertView = [[UIAlertView alloc] initWithTitle:@"响应触摸事件" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    }
    if (type == 0) {
        
        alertView.message = [NSString stringWithFormat:@"点击事件：\ntext:%@, rowIndex:%ld, colIndex:%ld", label.text, label.row, label.col];
    }
    else
        alertView.message = [NSString stringWithFormat:@"长按事件：\ntext:%@, rowIndex:%ld, colIndex:%ld", label.text, label.row, label.col];
    [alertView show];
}

#pragma mark - sort

//获取某一列的排序数组
- (NSArray *)arraySortedByAscInCol:(NSInteger)colIndex
{
    NSArray *sortedDatas = [reportView.dataSource.bodyDatas sortedArrayUsingComparator:^NSComparisonResult(id row1, id row2) {
        
        return ((MNReportGrid *)[row1 objectAtIndex:colIndex]).text.integerValue >= ((MNReportGrid *)[row2 objectAtIndex:colIndex]).text.integerValue ? 1 : -1;
    }];
    
    NSMutableArray *sortedArray = [[NSMutableArray alloc] init];
    
    for (NSArray *sortedRow in sortedDatas) {
        
        for (NSArray *row in reportView.dataSource.bodyDatas) {
            
            if ([sortedRow isEqual:row]) {
                
                [sortedArray addObject:[NSNumber numberWithInteger:[reportView.dataSource.bodyDatas indexOfObject:row] + 1]];
            }
        }
    }
    
    return sortedArray;
}

@end
